package cn.liangcaomei.oss.service.impl;

import cn.liangcaomei.oss.service.OssService;
import cn.liangcaomei.oss.utils.ConstantPropertiesUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //獲取工具類中的值
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {

            //創建Oss實例對象
            OSS ossClint = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

            //獲取上傳文件輸入流
            InputStream inputStream = file.getInputStream();

            //獲取文件名稱
            String fileName = file.getOriginalFilename();
            //1 在文件名稱裏面加上唯一值，解決可覆蓋問題
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            //拼接
            fileName = uuid + fileName;

            //2 文件按日期分類
            //獲取當前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            fileName = datePath + "/" + fileName;

            //調用oss方法上傳文件
            ossClint.putObject(bucketName,fileName,inputStream);

            //關閉oss
            ossClint.shutdown();

            //把文件上傳之後的路徑返回
            //拼接路徑
            //https://jack-edu.oss-cn-shenzhen.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
